package com.peisong.controller;


import com.peisong.domain.Result;
import com.peisong.domain.Test;
import com.peisong.service.TestService;
import com.peisong.utils.JwtUtil;
import com.peisong.utils.Md5Util;
import com.peisong.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test")
@Validated
public class TestController {

    @Autowired
    private TestService testService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){

        //查询用户
        Test test = testService.findByUsername(username);
        if(test==null){
            //没有占用
            //注册
            testService.register(username,password);
            return Result.success();
        }else {
            return Result.error("用户名已被占用");
        }
    }

    @RequestMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        //根据用户名查询用户
        Test loginTest = testService.findByUsername(username);
        //判断用户是否存在
        if(loginTest==null) {
            return Result.error("用户名错误");
        }
        //判断密码是否正确 password是加密后的密文
        if(Md5Util.getMD5String(password).equals(loginTest.getPassword())){
            //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginTest.getId());
            claims.put("username",loginTest.getUsername());
            //生成token
            String token = JwtUtil.genToken(claims);
            //把token存储到redis中
            stringRedisTemplate.opsForValue().set(token,token,30, TimeUnit.DAYS);
            return Result.success(token);
        }else {
            return Result.error("密码错误");
        }
    }

    @GetMapping("/userInfo")
    public Result<Test> userInfo(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Test test =testService.findByUsername(username);
        return Result.success(test);
    }

    /**
     * 更新用户信息
     * @param test
     * @return
     * @RequestBody:接收json格式的数据
     * @Validated:开启校验
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated Test test){
        testService.update(test);
        return Result.success();
    }
}
